<?php

namespace CHOMP\SGIBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use CHOMP\SGIBundle\Entity\Prioridad;
use CHOMP\SGIBundle\Form\PrioridadType;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use CHOMP\SGIBundle\Services\RolHelper;
use CHOMP\SGIBundle\Services\SessionManager;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Prioridad controller.
 *
 * @Route("/prioridad")
 */
class PrioridadController extends Controller
{
	/**
	 * 
	 * @var SessionManager
	 * @DI\Inject("session.manager")
	 */
	public $sessionSvc;

    public function listarAction(Request $request, $page)
    {
		if ($this->sessionSvc->userIsLogged()){
			$session = $request->getSession();
			$em = $this->getDoctrine()->getManager();
			$query = $em->createQueryBuilder()->select('u')->from('CHOMPSGIBundle:Prioridad','u')->where('u.empresa = '. $session->get('empresa').' AND u.borrado = 0');
	
			
			$paginador = new Pagerfanta(new DoctrineORMAdapter($query));
			$paginador->setMaxPerPage(10);
			$paginador->setCurrentPage($page); 
		
			return $this->render('CHOMPSGIBundle:Prioridad:listar.html.twig', array('entities' => $paginador));
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
    }
	
    /**
     * Creates a nueva Prioridad entity.
     *
     * @Route("/", name="prioridad_crear")
     * @Method("POST")
     * @Template("CHOMPSGIBundle:Prioridad:nuevo.html.twig")
     */
    public function crearAction(Request $request)
    {
        $entity = new Prioridad();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('prioridad_listar'));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a Prioridad entity.
    *
    * @param Prioridad $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Prioridad $entity)
    {
        $form = $this->createForm(new PrioridadType(), $entity, array(
            'action' => $this->generateUrl('prioridad_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Guardar', 'attr'=> array('class'=>'btn')));

        return $form;
    }

    /**
     * Displays a form to create a new Prioridad entity.
     *
     * @Route("/nuevo", name="prioridad_nuevo")
     * @Method("GET")
     * @Template()
     */
    public function nuevoAction()
    {
		if ($this->sessionSvc->userIsLogged()){
			$entity = new Prioridad();
			$entity->setBorrado(false);
			
			$form   = $this->createCreateForm($entity);
	
			return array(
				'entity' => $entity,
				'form'   => $form->createView(),
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
    }

    /**
     * Finds and displays a Prioridad entity.
     *
     * @Route("/{id}", name="prioridad_ver")
     * @Method("GET")
     * @Template()
     */
    public function verAction($id)
    {
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
	
			$entity = $em->getRepository('CHOMPSGIBundle:Prioridad')->find($id);
	
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find Prioridad entity.');
			}
	
			return array(
				'entity'      => $entity,
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
    }

    /**
     * Displays a form to edit an existing Prioridad entity.
     *
     * @Route("/{id}/editar", name="prioridad_editar")
     * @Method("GET")
     * @Template()
     */
    public function editarAction($id)
    {
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
	
			$entity = $em->getRepository('CHOMPSGIBundle:Prioridad')->find($id);
	
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find Prioridad entity.');
			}
	
			$editForm = $this->createEditForm($entity);
	
			return array(
				'entity'      => $entity,
				'edit_form'   => $editForm->createView()
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
    }

    /**
    * Creates a form to edit a Prioridad entity.
    *
    * @param Prioridad $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Prioridad $entity)
    {
        $form = $this->createForm(new PrioridadType(), $entity, array(
            'action' => $this->generateUrl('prioridad_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Guardar', 'attr'=> array('class'=>'btn middle-first')));

        return $form;
    }
    /**
     * Edits an existing Prioridad entity.
     *
     * @Route("/{id}", name="prioridad_update")
     * @Method("PUT")
     * @Template("CHOMPSGIBundle:Prioridad:editar.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CHOMPSGIBundle:Prioridad')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Prioridad entity.');
        }

        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('prioridad_listar'));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        );
    }
    /**
     * Deletes a Prioridad entity.
     *
     * @Route("/{id}", name="prioridad_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('CHOMPSGIBundle:Prioridad')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Prioridad entity.');
            }

            //$em->remove($entity);
			$entity->setBorrado(true);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('prioridad_listar'));
    }

    /**
     * Creates a form to delete a Prioridad entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('prioridad_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }

	public function borrarAction($id) {
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
			$idsArray = explode (',', $id);
	
			for ($i = 0; $i < count($idsArray); $i++){
				$priABorrar = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Prioridad')->find($idsArray[$i]);
				$priABorrar->setBorrado(1);
				$em->persist($priABorrar);
			}
	
			$em->flush();
					
			return $this->redirect($this->generateUrl('prioridad_listar'));	
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}
}
